const fs = require("fs").promises;
const { to, haveChinaStr } = require("./utils");
const config = require("./config");

// 过滤数据库类型
const dataBaseTypeDict = {
  integer: "number",
  string: "string",
};
function String(str) {
  return str + "";
}

// 生成interface文件
async function generatorInterfaceFile(schemas, docName, api) {
  // 文档地址
  const apiAddress = config.apiHtmlUrl;

  // 过滤带<<的key 带<<都用项目定义好的公有ts类型替代
  const keys = Object.keys(schemas).filter((key) => !key.includes("«"));

  const fileName = `./${docName}/interface.ts`;
  await to(fs.writeFile(fileName, ""));
  let content = `// swagger文档地址:${apiAddress}`;
  // 遍历表 即遍历PO 得出每个interface的内容
  keys.forEach((key, idx) => {
    // if (idx !== 0) return;
    const schema = schemas[key];
    const props = Object.keys(schema.properties);
    // 格式化美化注释 固定位置注释
    const maxProKeyLen = props.reduce((preProKey, curProKey) =>
      preProKey?.length > curProKey?.length ? preProKey : curProKey
    ).length;
    console.log({ maxProKeyLen });

    const proKeyOfMaxProKeyLen = props.reduce((preProKey, curProKey) =>
      String(dataBaseTypeDict[schema.properties[preProKey].type])?.length >
      String(dataBaseTypeDict[schema.properties[curProKey].type])?.length
        ? preProKey
        : curProKey
    );
    const maxProTypeLen = String(
      dataBaseTypeDict[schema.properties[proKeyOfMaxProKeyLen].type]
    )?.length;
    console.log({ maxProTypeLen });

    const maxPrefix = maxProKeyLen + maxProTypeLen;
    console.log({ maxPrefix });
    // 全部属性的内容
    const propsContent = props
      .map((propKey) => {
        // 属性值项
        const propItem = schema.properties[propKey];
        let annotationContent = `${propItem.description} `;
        delete propItem.description;
        annotationContent += Object.keys(propItem)
          .map((propItemKey) => ` ${propItemKey}:${propItem[propItemKey]}`)
          .join(" ");
        const whiteSpaceLen =
          maxPrefix -
          propKey?.length -
          String(dataBaseTypeDict[propItem.type])?.length;
        const whiteSpaceStr = Array(whiteSpaceLen + 2)
          .fill()
          .join(" ");
        // 每行属性的内容
        const propContent = `    // ${annotationContent}\n    ${propKey}: ${
          dataBaseTypeDict[propItem.type]
        },`;
        return propContent;
      })
      .join("\n");

    // 每张表的内容 每个interface的内容
    const schemaContent = `\n
/**
* description:${schema.description}
* title:${schema.title}
* */
export interface ${key}{\n${propsContent}\n}\n`;

    content += schemaContent;
  });
  await to(fs.writeFile(fileName, content));
}

module.exports = {
  dataBaseTypeDict,
  generatorInterfaceFile,
};
